﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HandLab.LocalApp.Learn
{
    public class LearnAtoZ
    {
        public static void DelegateTestGo ( )
        {
            new DelegateTest().Go("hello");
        }
    }

    #region Delegate
    public delegate void HelloDelegate ( string message );
    public delegate int Del ( int i );

    public class DelegateTest
    {
        public static void f1 ( string message )
        {
            Console.WriteLine(string.Format("f1:{0}", message));
        }

        public void f2 ( string message )
        {
            Console.WriteLine(string.Format("f2:{0}", message));
        }

        public void Go ( string message )
        {
            HelloDelegate ff1 = f1;
            HelloDelegate ff2 = f2;

            ff1(message);
            ff2(message);
            HelloDelegate ff3 = ff1 + ff2 + ff1;
            Console.WriteLine("-------------------------");
            ff3(message);
            Console.WriteLine("*************************");
            Console.WriteLine(ff1.GetInvocationList().LongLength);
            Console.WriteLine(ff2.GetInvocationList().LongLength);
            Console.WriteLine(ff3.GetInvocationList().LongLength);
            int i = 0;
            HelloDelegate d = delegate( string s ) { Console.WriteLine(string.Format("{0}:{1}", s, i++)); };
            d(message);

            Console.WriteLine("=========================");
            HelloDelegate p = delegate( string j )
            {
                System.Console.WriteLine(j);
            };

            // Results from the anonymous delegate call.
            p("The delegate using the anonymous method is called.");

            // The delegate instantiation using a named method "DoWork".
            p = new HelloDelegate(DoWork);

            // Results from the old style delegate call.
            p("The delegate using the named method is called.");

            Console.WriteLine("#########################");
            Del dd = x =>
            {
                Console.WriteLine(string.Format("x*x={0}", x * x));
                return x * x;
            };

           dd(2);
        }

        static void DoWork ( string k )
        {
            System.Console.WriteLine(k);
        }
    }

    #endregion
}
